package com.unitd.modules.configcenter.controller;

import com.github.pagehelper.PageInfo;
import com.unitd.frame.comm.utils.StringUtils;
import com.unitd.frame.springweb.controller.result.AjaxResult;
import com.unitd.frame.springweb.controller.result.PageResult;
import com.unitd.frame.sso.common.encrypt.Salt;
import com.unitd.modules.comm.exception.ConfigServerException;
import com.unitd.modules.comm.model.SelectOption;
import com.unitd.modules.comm.web.BaseController;
import com.unitd.modules.configcenter.entity.Profiles;
import com.unitd.modules.configcenter.entity.Users;
import com.unitd.modules.configcenter.service.IProfilesService;
import com.unitd.modules.configcenter.service.IUsersService;
import com.unitd.modules.sso.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @desc 配置中心用户信息管理前端控制器
 * @filename UserController.java
 * @copyright www.unitd.com
 * @version 1.0
 * @author Hudan
 * @date 2018/1/31
 */
@RestController
@RequestMapping("/admin/user")
public class UserController extends BaseController {

	@Autowired
	private IUsersService usersService;
	@Autowired
	private IProfilesService profilesService;

	/**
	 * @desc 获取信息列表json数据,方便列表页通过ajax获取并展示
	 * @param param 用户信息
	 * @return json数据
	 */
	@RequestMapping(value = "list", method = RequestMethod.GET)
	public PageResult list(Users param) {
		// 获取分页数据信息
		Map<String, Integer> pageMap = getPageMap();

		// 查询列表数据
		PageInfo<Users> pageData = usersService.getPageData(pageMap.get("pageNo"), pageMap.get("pageSize"), param);

		return new PageResult(pageData.getTotal(), pageData.getList());
	}

	/**
	 * @desc 根据主键ID,获取对应的详情信息
	 * @param id 主键ID
	 * @return 自定义的通用json对象
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public AjaxResult getData(@PathVariable("id") String id) {
		// 根据主键获取属性配置所属环境信息
		Users entity = usersService.selectByPrimaryKey(id);
		return new AjaxResult(entity);
	}

	/**
	 * @desc 新增/修改数据
	 * @param param 前端需要进行新增/修改的数据
	 * @return 自定义的通用json对象
	 */
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	public AjaxResult edit(@RequestBody Users param) {
		SecurityUtil.requireSuperAdmin();

		// 新增数据
		if(StringUtils.isNull(param.getId())) {
			param.setId(null);

			if (StringUtils.isBlank(param.getName())) {
				throw new ConfigServerException(1001, "用户名不能为空!");
			}

			Users data = usersService.findByUserName(param.getName());
			if (data != null) {
				throw new ConfigServerException(1002, "已存在用户名为[" + param.getName() + "]的管理用户!");
			}

			param.setPassword(Salt.md5SaltEncode(param.getName(), "123456")); 		// 后台新增用户,默认密码为123456, 然后使用用户名作为密码盐值,与密码一起进行盐值加密
			param.setStatus((short) 1); 											// 用户状态(1:正常, 2:失效)
			param.setType((short) 2); 												// 用户类型(非管理员)
			param.setCreatedAt(new Date()); 										// 新增时间
			usersService.insertSelective(param);
		} else {
			// 修改数据
			Users data = usersService.selectByPrimaryKey(param.getId());
			if(!param.getName().equalsIgnoreCase(data.getName())) {
				Users oldData = usersService.findByUserName(param.getName());
				if (oldData != null) {
					throw new ConfigServerException(1002, "已存在用户名为[" + param.getName() + "]的管理用户!");
				}
			}
			param.setUpdatedAt(new Date());
			usersService.updateByPrimaryKeySelective(param);
		}

		return new AjaxResult(true, "数据保存成功!");
	}

	/**
	 * @desc 根据主键ID,删除响应的数据
	 * @param id 主键ID
	 * @return 自定义的通用json对象
	 */
	@RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
	public AjaxResult delete(@PathVariable("id") String id) {
		SecurityUtil.requireSuperAdmin();

		int delete = usersService.deleteByPrimaryKey(id);
		if(delete > 0) {
			return new AjaxResult(true, "删除数据成功!");
		} else {

			return new AjaxResult(false, "删除数据失败!");
		}
	}

	/**
	 * @desc 获取有效的信息的下拉菜单列表信息
	 * @return 下拉菜单列表数据
	 */
	@RequestMapping(value = "options", method = RequestMethod.GET)
	public List<SelectOption> getSelectOptionData() {
		List<SelectOption> result = new ArrayList<>();
		List<Users> list = usersService.listAll();
		for (Users entity : list) {
			result.add(new SelectOption(entity.getId(), entity.getName()));
		}
		return result;
	}

	/**
	 * @desc 切换属性配置所属环境信息的状态
	 * @param id 主键ID
	 * @return 自定义的通用json对象
	 */
	@RequestMapping(value = "switch/{id}", method = RequestMethod.GET)
	public AjaxResult switchOver(@PathVariable("id") String id) {
		SecurityUtil.requireSuperAdmin();

		Users entity = usersService.selectByPrimaryKey(id);
		entity.setStatus(entity.getStatus() == 1 ? (short) 0 : (short) 1);
		usersService.updateByPrimaryKey(entity);

		return new AjaxResult(true, "数据切换成功!");
	}

	/**
	 * @desc 获取用户所有有效的权限
	 * @return 通用Restful对象
	 */
	@RequestMapping(value = "auth_options", method = RequestMethod.GET)
	public AjaxResult authOptions() {
		List<SelectOption> result = new ArrayList<>();
		List<Profiles> list = profilesService.findAllEnabledProfiles();
		for (Profiles entity : list) {
			result.add(new SelectOption(entity.getName(), entity.getAlias()));
		}
		return new AjaxResult(true, "获取用户权限信息成功!", result);
	}

	/**
	 * @desc 编辑用户权限后,重新授权
	 * @param param 指定用户及用户权限串
	 * @return 通用Restful对象
	 */
	@RequestMapping(value = "gant_permission", method = RequestMethod.POST)
	public AjaxResult gantPermission(@RequestBody Users param) {
		SecurityUtil.requireSuperAdmin();
		Users user = usersService.selectByPrimaryKey(param.getId());
		user.setGantEnvs(param.getGantEnvs());
		user.setUpdatedAt(new Date());
		usersService.updateByPrimaryKeySelective(user);

		return new AjaxResult(true, "给用户重新授成功!");
	}
}